const {Commodity} = require("../../../models/commodity");
const {User} = require("../../../models/User");

module.exports = async (req, res) => {
    const userId = req.query.user_id;
    var collections =  [];
    try{
       const comm = await User.findOne({user_id:userId},{collections:1,_id:0}).lean();
       let len = comm.collections.length;
       if(len !== 0){
        for(let i=0;i<len;i++){
            //根据商品信息集合的ISBN查询图书集合中对应ISBN的图书信息的规则
            let opt = [
             {$match:{"Art_No": comm.collections[i].Art_No}},
             { $lookup:{
                     from: "books",
                     localField: "ISBN",
                     foreignField: "ISBN",
                     as: "bookInfo" },},
             { $unwind:"$bookInfo"},
             { $project:{
                     "_id":0,
                     "Art_No":1,
                     "freight":1,
                     "customPrice":1,
                     "user_id":1,
                     "appearance":1,
                     "ISBN":1,
                     "title": "$bookInfo.title",
                     "author": "$bookInfo.author",
                     "img": "$bookInfo.img",
                     "publisher": "$bookInfo.publisher",
                 }
             },
         ]
         Commodity.aggregate(opt, (err,data) => {
             if(err){
                 console.log(err)
                 res.status(500).send({errCode:"1",msg:"服务器内部错误"})
             }else{
                 collections.push(data[0])
                 if(i == len-1){
                  res.send({errCode:"0",msg:"success",data:{collections:collections}})
                 }
             }
         })
         }
       }else{
        res.send({errCode:"0",msg:"success",data:{collections:[]}})
       }
       
    }catch(e){
        console.log(e);
        res.status(400).send({errCode:"1",msg:"请求错误"})
    }
}